package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description：jwt拦截器
 * @Author: liulei
 * @Date: 2019年10月31日
 * @Version: V1.0
 **/
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器");
        //无论如何都放行，具体能不能操作还是在具体的操作中判断；
        //拦截器只是负责把请求头中有token的令牌进行解析验证；
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {//有头信息,且按规定的格式开头
            //得到token
            String token = header.substring(7);
            try {
                Claims claims = jwtUtil.parseJWT(token);
                //如果是管理员
                if (claims != null && "admin".equals(claims.get("roles"))) {
                    request.setAttribute("claims_admin", claims);
                }
                //如果是普通用户
                if (claims != null && "user".equals(claims.get("roles"))) {
                    request.setAttribute("claims_user", claims);
                }
            } catch (Exception e) {
                throw new RuntimeException("令牌不正确");
            }
        }
        return true;
    }
}
